package aes

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"duanju-mq/pkg/crypto/padding/pkcs5"
	"encoding/base64"
	"errors"
	"io"
	"strconv"
)

type AES struct {
	Key []byte
	IV  []byte
}

func (a *AES) Encrypt(plaindata []byte) ([]byte, error) {
	block, err := aes.NewCipher(a.Key)
	if err != nil {
		return nil, err
	}
	if a.IV == nil {
		a.IV = make([]byte, aes.BlockSize)
	}
	if len(a.IV) != aes.BlockSize {
		return nil, errors.New("iv length must equal block size")
	}
	data := pkcs5.Pad(plaindata, aes.BlockSize)
	cipherdata := make([]byte, len(data))
	cipher.NewCBCEncrypter(block, a.IV).CryptBlocks(cipherdata, data)
	return cipherdata, nil
}

func (a *AES) Decrypt(cipherdata []byte) ([]byte, error) {
	block, err := aes.NewCipher(a.Key)
	if err != nil {
		return nil, err
	}
	if a.IV == nil {
		a.IV = make([]byte, aes.BlockSize)
	}
	if len(a.IV) != aes.BlockSize {
		return nil, errors.New("iv length must equal block size")
	}
	if len(cipherdata)%aes.BlockSize != 0 {
		return nil, errors.New("ciphertext is not a multiple of the block size, " + strconv.Itoa(len(cipherdata)))
	}
	plaindata := make([]byte, len(cipherdata))
	cipher.NewCBCDecrypter(block, a.IV).CryptBlocks(plaindata, cipherdata)
	return pkcs5.Unpad(plaindata, aes.BlockSize)
}

func NewIV() []byte {
	iv := make([]byte, aes.BlockSize)
	io.ReadFull(rand.Reader, iv)
	return iv
}

func EncryptToString(key []byte, plaindata []byte) (string, error) {
	b, err := EncryptToBytes(key, plaindata)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(b), nil
}

func DecryptString(key []byte, cipherstring string) ([]byte, error) {
	b, err := base64.StdEncoding.DecodeString(cipherstring)
	if err != nil {
		return nil, err
	}
	return DecryptBytes(key, b)
}

func EncryptToBytes(key []byte, plaindata []byte) ([]byte, error) {
	a := &AES{Key: key, IV: NewIV()}
	cipherdata, err := a.Encrypt(plaindata)
	if err != nil {
		return nil, err
	}
	return append(a.IV, cipherdata...), nil
}

func DecryptBytes(key []byte, cipherdata []byte) ([]byte, error) {
	if len(cipherdata) < aes.BlockSize*2 {
		return nil, errors.New("ciphertext too short")
	}
	return (&AES{Key: key, IV: cipherdata[:aes.BlockSize]}).Decrypt(cipherdata[aes.BlockSize:])
}
